package dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bean.Intersection;
import dao.IntersectionDao;
import exception.DBException;

public class IntersectionDaoImpl extends HibernateDaoSupport implements IntersectionDao {
	private StaticData staticData;

	@Override
	public boolean save(List<Intersection> ls) throws DBException {
		this.getHibernateTemplate().saveOrUpdateAll(ls);
		return true;
	}

	@Override
	public boolean removeAll() throws DBException {
		this.getHibernateTemplate().deleteAll(
				this.getHibernateTemplate().find("from Intersection"));
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Intersection> query(int area) throws DBException {
		if (staticData == null) {
			List<Intersection> ls = this.getHibernateTemplate().find("from Intersection");
			List<Intersection> temp = new ArrayList<Intersection>();
			for (Intersection l : ls) {
				if (l.getE1() != null) {
					if (l.getE1().getArea().getId() != area) {
						temp.add(l);
						continue;
					}

				}
				if (l.getE2() != null) {
					if (l.getE2().getArea().getId() != area) {
						temp.add(l);
						continue;
					}

				}
				if (l.getW1() != null) {
					if (l.getW1().getArea().getId() != area) {
						temp.add(l);
						continue;
					}

				}
			}
			ls.removeAll(temp);
			return ls;
		} else {
			return staticData.getAllLights(area);
		}
	}

	public StaticData getStaticData() {
		return staticData;
	}

	public void setStaticData(StaticData staticData) {
		this.staticData = staticData;
	}

}
